import React, { Component } from 'react'
import {Button, Popconfirm} from 'antd'
// 引入全屏插件
import screenfull from 'screenfull'
import {FullscreenOutlined,FullscreenExitOutlined} from '@ant-design/icons'
import './css/header.less'
import { connect} from 'react-redux'
import {deleteUserInfo} from '../../../redux/actions_creators/login'
import dayjs from 'dayjs'
import {reqWeather} from '../../../api'
import {withRouter} from 'react-router-dom'
import menuList from '../../../config/menuConfig'
@connect(
  state => ({userInfo: state.userInfo, titleInRedux: state.title}),
  {
    deleteUserInfo
  }
)
@withRouter
class Header extends Component
{
  state = {
    isFull: false,
    date: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
    weather: '',
    title: ''
  }
  // 点击实现全屏的功能
  fullScreen = () => {
    if (screenfull.isEnabled) {
      screenfull.toggle()
    }
  }
  logout = () => {
    this.props.deleteUserInfo()
  }
  getWeather = async () => {
    const weather = await reqWeather()
    this.setState({weather})
  }
  getTitle = () => {
    const path = this.props.location.pathname
    let res =  ''
    menuList.forEach(item => {
      if(item.children) {
        item.children?.forEach(child => {
          if (child.key === path) {
            res = child.title
          }
        })
      } else {
        if (item.key === path) {
          res = item.title
        }
      }
    })
    this.setState({title: res})
    return res
  }
  componentDidMount() {
    // 绑定事件
    screenfull.on('change', () => {
      if (screenfull.isFullscreen) {
        this.setState({isFull: true})
      } else {
        this.setState({isFull: false})
      }
    })
    this.timer = setInterval(() => {
      this.setState({date: dayjs().format('YYYY年MM月DD日 HH:mm:ss')})
    }, 1000)
    // this.getWeather()
    this.getTitle()
  }
  componentWillUnmount() {
    clearInterval(this.timer)
  }
  render() {
    return (
      <header className="header">
        <div className="header-top">
          <Button size="small" onClick={this.fullScreen}>
            {
              this.state.isFull? <FullscreenExitOutlined />:<FullscreenOutlined />
            }
          </Button>
          <span className="username">欢迎，{this.props.username}</span>
          <Popconfirm
            title="确定要退出登录吗？"
            onConfirm={this.logout}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" type="link">退出登录</Button>
          </Popconfirm>

        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{this.props.titleInRedux || this.state.title}</div>
          <div className="header-bottom-right">
            <span className="date">⏰{this.state.date}</span>
            <div className="weather">天气⛅多云{this.state.weather.weather}</div>
            <div className="temperature">气温🌡{this.state.weather.temperature} 29℃</div>
          </div>
        </div>
      </header>
    )
  }
}
export default Header